package com.tdk.bts.view;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.tdk.bts.action.BookInfoAction;
import com.tdk.bts.action.FilmScreenAction;
import com.tdk.bts.entity.BookInfo;
import com.tdk.bts.entity.Film;
import com.tdk.bts.entity.FilmScreen;
import com.tdk.bts.entity.Seat;
import com.tdk.bts.entity.Theater;
import com.tdk.bts.util.ImageUtil;
import com.tdk.bts.util.Request;
import com.tdk.bts.util.StringUtil;

public class SeatChoiceView {

	private JFrame jf;
	
	private JLabel screenLabel;
	
	private JPanel leftPanel ;

	private JComboBox daysBox;
	
	private int filmId;
	
	private List<ScreenLabel> screenLabels = new ArrayList<ScreenLabel>();
	
	private JLabel[][] seatLabel;
	
	private JLabel submitLabel;
	
	private List<String> books;
	
	private int screenId;
	
	private JLabel theaterLabel;
	
	
	private FilmScreenAction filmScreenAction = new FilmScreenAction();
	
	private BookInfoAction bookInfoAction = new BookInfoAction();
	
	private Film film;
	
	public SeatChoiceView(Film film) {
		this.filmId = film.getId();
		this.film = film;
	}
	
	
	
	public void show()
	{
		init();
		setStyle();
		bindData();
		registHandler();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void init() {
		jf = new JFrame(film.getName());
		screenLabel = new JLabel();
		leftPanel = new JPanel();
		daysBox = new JComboBox();
		submitLabel = new JLabel();
		books = new ArrayList<String>();
		theaterLabel = new JLabel();
	}

	private void bindData()
	{
		try {
			daysBox.removeAllItems();
			daysBox.addItem("-------请选择-------");
			Request request = new Request();
			request.setParameter("filmId", filmId);
			filmScreenAction.findDaysByFilmId(request);
			List<String> days = (List<String>) request.getAttribute("days");
			for (int i = 0; i < days.size(); i++) {
				daysBox.addItem(days.get(i));
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
		
	}
	
	private void setStyle() {
		jf.setSize(930, 400);
		jf.setLocationRelativeTo(null);
		jf.setLayout(null);
		jf.getContentPane().setBackground(Color.WHITE);
		jf.getContentPane().setVisible(true);


		leftPanel.add(daysBox);
		leftPanel.setBounds(0, 0, 130, 400);
		jf.add(leftPanel);
		
		theaterLabel.setForeground(new Color(0x3385ff));
		theaterLabel.setBounds(480, 50, 100, 50);
		jf.add(theaterLabel);
		
		screenLabel.setBounds(130, 0, 770, 71);
		screenLabel.setIcon(ImageUtil.getImage("screen.png",770,71));
		screenLabel.setOpaque(true);
		screenLabel.setBackground(Color.WHITE);
		jf.add(screenLabel);
		
		
		
		submitLabel.setIcon(ImageUtil.getImage("submitBtn.png"));
		submitLabel.setBounds(480, 300, 99, 33);
		submitLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
		jf.add(submitLabel);
		
	}
	private void registHandler() {
		daysBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String item = daysBox.getSelectedItem().toString();
				if(!item.contains("请选择"))
				{
					Request request = new Request();
					request.setParameter("filmId", filmId);
					try {
						while(leftPanel.getComponentCount()>1){
							leftPanel.remove(1);
						}
						
						
						request.setParameter("day", daysBox.getSelectedItem());
						filmScreenAction.findScreensByStartDay(request);
						List<FilmScreen> screens = (List<FilmScreen>) request.getAttribute("screens");
						screenLabels.clear();
						if(screens!=null)
						{
							for (int i = 0; i < screens.size(); i++) {
								ScreenLabel sc = new ScreenLabel(screens.get(i));
								screenLabels.add(sc);
								leftPanel.add(sc);
							}
							
							
							for (int i = 0; i < screenLabels.size(); i++) {
								final ScreenLabel sc = screenLabels.get(i);
								sc.addMouseListener(new MouseAdapter() {
									@Override
									public void mouseClicked(MouseEvent e) {
										
										books = new ArrayList<String>();
										
										for (int j = 0; j < screenLabels.size(); j++) {
											screenLabels.get(j).setForeground(Color.black);
										}
										sc.setForeground(Color.RED);
										screenId = sc.getScreenId();
										bindSeat();
									}
								});
							}
							
							leftPanel.repaint();
							leftPanel.validate();
						}
						
					} catch (Exception e1) {
						e1.printStackTrace();
						JOptionPane.showMessageDialog(null, e1.getMessage());
					}
					
				}
			}
		});
	
	
		submitLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				
				if(books.isEmpty())
				{
					JOptionPane.showMessageDialog(null, "您还没有选择任何座位", "错误", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				StringBuffer msg = new StringBuffer();
				msg.append("确认选择\n");
				
				for (int i = 0; i < books.size(); i++) {
					String seat[] = books.get(i).split(",");
					msg.append((Integer.parseInt(seat[0])+1)+"排"+seat[1]+"号\n");
				}
				
				msg.append("共：" + books.size() + "个座位么?");
				
				int choice = JOptionPane.showConfirmDialog(null, msg, "确认", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
				if(choice == JOptionPane.YES_OPTION)
				{
					
					Request request = new Request();
					request.setParameter("screenId",screenId);
					request.setParameter("seats", books);
					String phone = null;
					while(phone == null || "".equals(phone.trim()) || !phone.matches("\\d{11}") )
					{
						phone = JOptionPane.showInputDialog("请输入11位手机号", "131");
					}
					request.setParameter("phone", phone);
					try {
						bookInfoAction.book(request);
						String validCode = (String) request.getAttribute("validCode");
						System.out.println("预定成功:\n电话: " + phone + "\n取票码: " + validCode + "\n请务必保存好取票码，以便取票");
						JOptionPane.showMessageDialog(null,new JLabel("<html>预定成功:<br>电话: " + phone + "<br>取票码: " + validCode + "<br><font color='red'>请务必保存好取票码，以便取票</font></html>"), "成功", JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception e1) {
						e1.printStackTrace();
						JOptionPane.showMessageDialog(null, e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
					}
					bindSeat();
					
				}
			}
		});
	
	}
	
	
	private void bindSeat() {
		books = new ArrayList<String>();
		try {
			
			if(seatLabel != null)
			{
				for (int i = 0; i < seatLabel.length; i++) {
					for (int j = 0; j < seatLabel[i].length; j++) {
						jf.remove(seatLabel[i][j]);
					}
				}
			}
			
			Request request = new Request();
			request.setParameter("screenId", screenId);
			filmScreenAction.findTheaterAndBookInfoByScreenId(request);
			
			Theater t = (Theater) request.getAttribute("theater");
			
			theaterLabel.setText(t.getName());
			
			List<BookInfo> bks = (List<BookInfo>) request.getAttribute("bookInfos");
			
			int width = 700 / t.getColumns();
			int height = 200 / t.getRows();
			
			seatLabel = new JLabel[t.getRows()][t.getColumns()];
			
			for (int i = 0; i < t.getRows(); i++) {
				for (int j = 0; j < t.getColumns(); j++) {
					JLabel st = new JLabel();
					st.setIcon(ImageUtil.getImage("active.png"));
					st.setCursor(new Cursor(Cursor.HAND_CURSOR));
					st.setBounds(150+j*width,100+i*height, 30, 30);
					jf.add(st);
					st.setName("active");
					seatLabel[i][j] = st;
				}
			}
			
			for (int i = 0; i < bks.size(); i++) {
				BookInfo bi = bks.get(i);
				seatLabel[bi.getSeatX()][bi.getSeatY()].setIcon(ImageUtil.getImage("inactive.png"));
				seatLabel[bi.getSeatX()][bi.getSeatY()].setName("inactive");
			}
			
			for (int i = 0; i < seatLabel.length; i++) {
				for (int j = 0; j < seatLabel[i].length; j++) {
					final JLabel seaJLabel = seatLabel[i][j];
					final int seatX = i;
					final int seatY = j;
					seaJLabel.addMouseListener(new MouseAdapter() {
						
						@Override
						public void mouseClicked(MouseEvent e) {
							if("active".equals(seaJLabel.getName()))
							{
								seaJLabel.setIcon(ImageUtil.getImage("choice.png"));
								seaJLabel.setName("choice");
								books.add(seatX + "," + seatY);
								
								return;
							}
							
							if("choice".equals(seaJLabel.getName()))
							{
								seaJLabel.setIcon(ImageUtil.getImage("active.png"));
								seaJLabel.setName("active");
								books.remove(seatX + "," + seatY);
							}
							
							if("inactive".equals(seaJLabel.getName()))
							{
								JOptionPane.showMessageDialog(null, "该座位已经被预定！");
							}
							
						}
						
					});
				}
			}
			
			jf.repaint();
			jf.validate();
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
		
	}
	
}
class ScreenLabel extends JLabel{
	private int screenId;

	public ScreenLabel(FilmScreen sc) {
		super(sc.getTime().toString());
		this.screenId = sc.getId();
		this.setCursor(new Cursor(Cursor.HAND_CURSOR));
		ScreenLabel.this.setOpaque(true);
	}
	
	public int getScreenId()
	{
		return this.screenId;
	}
	
}
